/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tencent.wcdb;

import java.io.File;
import java.util.List;

import com.tencent.wcdb.database.SQLiteDatabase;
import com.tencent.wcdb.database.SQLiteException;
import com.tencent.wcdb.database.SQLiteTrace;
import com.tencent.wcdb.support.Log;

import android.util.Pair;


/**
 * Default class used to define the actions to take when the database corruption is reported
 * by sqlite.
 * <p>
 * An application can specify an implementation of {@link DatabaseErrorHandler} on the
 * following:
 * <ul>
 *   <li>{@link SQLiteDatabase#openOrCreateDatabase(String,
 *      com.tencent.wcdb.database.SQLiteDatabase.CursorFactory, DatabaseErrorHandler)}</li>
 *   <li>{@link SQLiteDatabase#openDatabase(String,
 *      com.tencent.wcdb.database.SQLiteDatabase.CursorFactory, int, DatabaseErrorHandler)}</li>
 * </ul>
 * The specified {@link DatabaseErrorHandler} is used to handle database corruption errors, if they
 * occur.
 * <p>
 * If null is specified for DatabaeErrorHandler param in the above calls, then this class is used
 * as the default {@link DatabaseErrorHandler}.
 */
public final class DefaultDatabaseErrorHandler implements DatabaseErrorHandler {

    private static final String TAG = "WCDB.DefaultDatabaseErrorHandler";

	private final boolean mNoCorruptionBackup;

    public DefaultDatabaseErrorHandler() {
        mNoCorruptionBackup = false;
    }

    public DefaultDatabaseErrorHandler(boolean noCorruptionBackup) {
        mNoCorruptionBackup = noCorruptionBackup;
    }

    /**
     * defines the default method to be invoked when database corruption is detected.
     * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption
     * is detected.
     */
	@Override
    public void onCorruption(SQLiteDatabase dbObj) {
        Log.e(TAG, "Corruption reported by sqlite on database: " + dbObj.getPath());

        // is the corruption detected even before database could be 'opened'?
        if (!dbObj.isOpen()) {
            // database files are not even openable. delete this database file.
            // NOTE if the database has attached databases, then any of them could be corrupt.
            // and not deleting all of them could cause corrupted database file to remain and 
            // make the application crash on database open operation. To avoid this problem,
            // the application should provide its own {@link DatabaseErrorHandler} impl class
            // to delete ALL files of the database (including the attached databases).
            deleteDatabaseFile(dbObj.getPath());
            return;
        }

        // Close the database, which will cause subsequent operations to fail.
        // before that, get the attached database list first.
        List<Pair<String, String>> attachedDbs = null;
        try { attachedDbs = dbObj.getAttachedDbs(); } catch (SQLiteException e) {}

		// Invoke callback.
		SQLiteTrace trace = dbObj.getTraceCallback();
		if (trace != null) {
			trace.onDatabaseCorrupted(dbObj);
		}

        try {
            dbObj.close();
        } catch (SQLiteException e) {
        } finally {
            // Delete all files of this corrupt database and/or attached databases
            if (attachedDbs != null) {
                for (Pair<String, String> p : attachedDbs) {
                    deleteDatabaseFile(p.second);
                }
            } else {
                // attachedDbs = null is possible when the database is so corrupt that even
                // "PRAGMA database_list;" also fails. delete the main database file
                deleteDatabaseFile(dbObj.getPath());
            }
        }
    }

    private static final String[] SUFFIX_TO_BACKUP = new String[] {
            "", "-journal", "-wal", ".sm", ".bak", "-vfslog", "-vfslo1"
    };

	private void deleteDatabaseFile(String fileName) {
		if (fileName.equalsIgnoreCase(":memory:") || fileName.trim().length() == 0) {
			return;
		}

		Log.e(TAG, "Remove database file: " + fileName);

        if (!mNoCorruptionBackup) {
            // Save corrupted database for recovery.
            File originFile = new File(fileName);
            File corruptedDir = new File(originFile.getParentFile(), "corrupted");
            if (!corruptedDir.mkdirs()) {
                Log.e(TAG, "Could not create directory for corrupted database. " +
                        "Corruption backup may be unavailable.");
            }

            String corruptedPath = corruptedDir.getPath() + "/" + originFile.getName();
            for (String suffix : SUFFIX_TO_BACKUP) {
                moveOrDeleteFile(fileName + suffix, corruptedPath + suffix);
            }
        } else {
            for (String suffix : SUFFIX_TO_BACKUP) {
                deleteFile(fileName + suffix);
            }
        }
	}

	private static boolean moveOrDeleteFile(String oldPath, String newPath) {
		File oldFile = new File(oldPath);
		boolean ret = oldFile.renameTo(new File(newPath));
		if (!ret) {
            oldFile.delete();
        }
		return ret;
	}

    private static boolean deleteFile(String path) {
        return new File(path).delete();
    }
}
